package com.zx.idc.backend.gui.scheduler.ins.filtermonitorlog.job;


import com.zx.idc.backend.gui.scheduler.ins.filtermonitorlog.job.base.BaseFilterAndMonitorInstructionJob;
import com.zx.idc.common.constants.InsSourceConstants;
import com.zx.idc.common.exception.EncryptException;
import com.zx.idc.common.lang.ListUtil;
import com.zx.idc.ds.ins.entity.InsFilter;
import com.zx.idc.ds.ins.entity.InsFilterRule;
import com.zx.idc.ds.ins.service.IInsFilterRuleService;
import com.zx.idc.ds.ins.service.IInsFilterService;
import com.zx.idc.ds.sys.entity.SysKeywordRepo;
import com.zx.idc.ds.sys.service.ISysKeywordRepoService;
import com.zx.idc.internal.exception.SendMessageException;
import com.zx.idc.internal.ins.InstructionCallResult;
import com.zx.idc.internal.service.SMMSFilterInstructionService;
import com.zx.idc.qc.constants.ScheduleJobConstants;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 从拦截器删除安全指令规则
 * <p>
 * 该指令在集群环境下，一次只能一个节点执行
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class DelFilterInstructionJob extends BaseFilterAndMonitorInstructionJob implements Job {

    private static final Logger LOG = LoggerFactory.getLogger(DelFilterInstructionJob.class);

    @Autowired
    private SMMSFilterInstructionService smmsFilterInstructionService;

    @Autowired
    private ISysKeywordRepoService iSysKeywordRepoService;

    @Autowired
    private IInsFilterService iInsFilterService;

    @Autowired
    private IInsFilterRuleService iInsFilterRuleService;


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String commandId = (String) jobDataMap.get(ScheduleJobConstants.INSTRUCTION_COMMAND_ID_KEY);
        InsFilter insFilter = (InsFilter) jobDataMap.get(ScheduleJobConstants.INSTRUCTION_ENTITY);
        if (insFilter == null) {
            LOG.error("执行删除过滤规则任务失败，命令id：{} 在数据库中不存在", commandId);
            return;
        }
        List<InsFilterRule> insFilterRules = insFilter.getInsFilterRules();
        if (InsFilter.INS_SOURCE_SMMS.equals(insFilter.getInsSource()) && ListUtil.isEmpty(insFilterRules)) {
            //删除关键词
            List<SysKeywordRepo> sysKeywordRepos = iSysKeywordRepoService.selectList(new SysKeywordRepo().setInsId(commandId));
            if (sysKeywordRepos != null) {
                iSysKeywordRepoService.deleteBatchIds(
                    sysKeywordRepos.stream().map(SysKeywordRepo::getId).collect(Collectors.toList())
                );
            }
        }
        //删除指令记录
        if (InsSourceConstants.SMMS.equals(insFilter.getInsSource())) {
            iInsFilterService.deleteById(insFilter.getId());
        }
        if (insFilterRules != null) {
            iInsFilterRuleService.deleteBatchIds(insFilterRules.stream().map(InsFilterRule::getId).collect(Collectors.toList()));
        }
        for (String houseId : insFilter.getHouseId().split(",")) {
            try {
                InstructionCallResult result = smmsFilterInstructionService.delRules(insFilter, houseId);
                if (result != null && result.getCode() == 200) {
                    LOG.info("执行删除过滤规则任务成功，命令id：{}", commandId);
                    continue;
                }
            } catch (EncryptException e) {
                LOG.error("删除过滤规则任务执行失败，原因：保存的过程中，数据加密报错。具体错误：" + e.getMessage(), e);
            } catch (SendMessageException e) {
                LOG.error("删除过滤规则任务执行失败。具体错误：" + e.getMessage(), e);
            }
            addTLogAlarm("删除过滤规则任务", "删除过滤规则任务执行失败");
        }
    }

}
